new Vue({
    el: "#app",
    data: {
        school: [
            {
                id: 1,
                name: '小米',
                price: 1500,
                num: 1,
                zhuangtai: false
            },
            {
                id: 2,
                name: '小米1',
                price: 2500,
                num: 1,
                zhuangtai: false
            },
            {
                id: 3,
                name: '小米2',
                price: 3500,
                num: 1,
                zhuangtai: false
            }
        ],
        quan: false,
        zhong: 0
    },
    methods: {
        //数量减少
        jian(index) {
            this.school[index].num==1?1:this.school[index].num--;
        },
        //数量增加
        add(index) {
            this.school[index].num++;
        },
        //删除商品
        remove(index) {
            this.school.splice(index, 1);
        },
        //是否全选
        qx() {
            if (this.quan) {
                this.school.forEach(va => {
                    va.zhuangtai = false;
                })
            } else {
                this.school.forEach(va => {
                    va.zhuangtai = true;
                })
            }
        }
    },
    computed: {
        //计算总价
        zong() {
            // pre为上一个数据，ele就是数组
            return this.school.reduce((pre,ele)=>{
                return ele.zhuangtai?ele.num*ele.price:pre
            },0)
        }
    },
    //监听
    watch: {
        school: {
            handler: function (value) {
                let zt=0;
                //循环遍历查询是否全选状态
                value.forEach(element=>{
                    //如果有一个状态为false则取消全选状态
                    if(element.zhuangtai){
                        zt++;
                    }
                })
                //根据状态设置全选状态
                if(zt==value.length){
                    this.quan=true;
                }else{
                    this.quan=false;
                }
            },
            //开启深度监听
            deep: true,
        }

    }
})